package cn.org.spring.wechar.controller;

import cn.org.spring.common.util.XmlUtils;
import cn.org.spring.wechar.constat.MessageType;
import cn.org.spring.wechar.context.ContextMessageFactory;
import cn.org.spring.wechar.service.message.ImageMessageService;
import cn.org.spring.wechar.service.message.TextMessageService;
import cn.org.spring.wechar.utils.AccessAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping("/weChar")
public class WeCharController {

    //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd1db2a66b0796762&secret=7c6b73de18dc9c8c6dcc8ff2067678b0
    private String token = "xiaohui";
    @Autowired
    private ContextMessageFactory contextMessageFactory;

    @GetMapping
    public String getWeChar(@RequestParam String signature,
                            @RequestParam String timestamp,
                            @RequestParam String nonce,
                            @RequestParam String echostr) {
        System.out.println("signature :" + signature);
        System.out.println("timestamp :" + timestamp);
        System.out.println("nonce :" + nonce);
        System.out.println("echostr :" + echostr);
        if (AccessAuthentication.of(token, timestamp, nonce, signature).checkSignature()) {
            return echostr;
        }
        return null;
    }

    @PostMapping
    public String post(@RequestBody String message) throws Exception {
        System.out.println("接收到微信公众平台消息：" + message);
        Map<String, Object> stringObjectMap = XmlUtils.xmlStrToMap(message);
        MessageType messageType = MessageType.getType(stringObjectMap.get("MsgType").toString());
        return contextMessageFactory.doAction(messageType,stringObjectMap);
    }


    /**
     * 服务检查接口
     *
     * @return
     */
    @GetMapping("/isWorker")
    public String isWorker() {
        return "Is Worker !";
    }

}
